#include <iostream>
#include <cstdlib>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
using namespace std;

int main()
{
    int key = 1234;
    int shmid = shmget(key, 4096, IPC_CREAT | IPC_EXCL | 0666);
    // 创建失败就返回
    if (shmid < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        exit(2);
    }
    cout << "create success" << endl;
    // 创建成功后就挂接到当前进程
    cout << "开始挂接" << endl;
    char *s = (char*)shmat(shmid, nullptr, 0);
    cout << "可以开始向共享内存写入数据了" << endl;
    fgets(s, 4096, stdin);
    cout << "输入的信息是: " << s << endl;
    cout << "即将解除关联" << endl;
    sleep(1);
    cout << "解除关联" << endl;
    shmdt(s);
    sleep(1);
    cout << "进程退出" << endl;
    sleep(2);
    return 0;
}